﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Utils
{
    /// <summary>
    /// 缓存管理类
    /// </summary>
    public class CacheHelper
    {
        /// <summary>
        /// 增加缓存 
        /// </summary>
        /// <param name="cacheKey">缓存的Key</param>
        /// <param name="obj">缓存的对象</param>
        /// <param name="minutes">缓存时间（分钟）</param>
        /// <returns></returns>
        public static void Insert(string cacheKey, object obj, int minutes)
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Cache.Insert(cacheKey, obj, null, DateTime.Now.AddMinutes(minutes), TimeSpan.Zero);
            }
        }

        /// <summary>
        /// 增加缓存
        /// </summary>
        /// <param name="cacheKey">缓存的Key</param>
        /// <param name="objObject">缓存的对象</param>
        /// <param name="absoluteExpiration"></param>
        /// <param name="slidingExpiration"></param>
        public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Cache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
            }
        }

        /// <summary>
        /// 得到缓存对象
        /// </summary>
        /// <param name="_cacheKey">缓存的Key</param>
        /// <returns></returns>
        public static object GetCacheByKey(string cacheKey)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Cache.Get(cacheKey);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 移除指定的缓存
        /// </summary>
        /// <param name="_cacheKey">缓存的Key</param>
        /// <returns></returns>
        public static object RemoveCacheByKey(string cacheKey)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Cache.Remove(cacheKey);
            }
            else
            {
                return null;
            }
        }
    }
}
